/* global window */
import modelExtend from 'dva-model-extend'
import pathToRegexp from 'path-to-regexp'
import { list, create, update, remove } from 'services/accout'
import { message } from 'antd'
import { pageModel } from './common'
import { config } from 'utils'
import * as basicData from 'services/basicData.js'
import queryString from 'query-string'


export default modelExtend(pageModel, {
  namespace: 'accoutData',

  state: {
    parentId: '',
    accountTypeData: [],
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((pathname) => {
        const match = pathToRegexp('/accout/:id').exec(pathname.pathname)
        if (match) {
          dispatch({ type: 'list', payload: { id: match[1] } })
          dispatch({ type: 'iniBasicData' })
        }
      })
    },
  },

  effects: {
    * list ({ payload = {} }, { call, put }) {
      const data = yield call(list, payload)
      const listData = data.data
      if (data) {
        yield put({
          type: 'updateState',
          payload: {
            parentId: payload.id,
            list: listData,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: listData.total,
            },
          },
        })
      }
    },
    * delete ({ payload }, { call, put, select }) {
      FormItem('enter')
      const data = yield call(remove, { ...payload })
      if (data.success) {
        message.success('delete success')
        yield put({ type: 'list' })
      } else {
        message.error('delete falied')
        throw data
      }
    },
    * iniBasicData({ payload = {} }, { call, put }) {
      const accountType = yield call(basicData.listall, { type: 'AccountType' })
      if (accountType.success) {
        yield put({
          type: 'updateState',
          payload: {
            accountTypeData: accountType.data,
          },
        })
      }
    },
  },

  reducers: {
  },
})
